package com.asit.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.asit.secure.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * 连接时验证用户是否登录
 *
 * @author LEITAO
 * @date 2018年4月18日 上午10:10:37
 */
@Slf4j
public class SessionAuthHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {

        //UserDO user = ShiroUtils.getUser();
        //获取session对象
        if(ObjectUtil.isEmpty(SecurityUtil.currentUserObj())){
            log.error("websocket权限拒绝:用户未登录");
            return false;
        }else{
            JSONObject user = BeanUtil.toBean(SecurityUtil.currentUserObj(), JSONObject.class);
            //SecurityUtil.pool.put(user.getStr("username"),"");
            log.info("{}",user);
            attributes.put("user", user.getStr("username"));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {

    }

}
